package com.open.model;

import java.io.Serializable;

import static com.open.constants.SysCode.*;

/**
 * @author dashu
 * @date 2025/1/2 18:29
 * @description 全局返回结果
 */
public class Result<T> implements Serializable {
    private static final long serialVersionUID = -3148615207069237662L;
    //状态码
    private String code;
    //错误信息
    private String msg;
    //返回数据
    private T data;
    //服务器处理时间 以毫秒为单位
    private Long time;

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Result() {
        this.code = SYSTEM_SUCCESS;
    }

    public Result(T data) {
        this.code = SYSTEM_SUCCESS;
        this.data = data;
    }

    public Result(T data, Long time) {
        this.code = SYSTEM_SUCCESS;
        this.data = data;
        this.time = time;
    }

    public Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> success() {
        return Result.success(null);
    }

    public static <T> Result<T> success(T data) {
        return Result.success(MSG, data, null);
    }

    public static <T> Result<T> success(String message, T data, Long time) {
        Result<T> result = new Result<>(data);
        result.setCode(SYSTEM_SUCCESS);
        result.setMsg(message);
        result.setTime(time);
        return result;
    }

    public static <T> Result<T> error(String msg) {
        return error(SYSTEM_ERROR, msg, null);
    }

    public static <T> Result<T> error(String code, String msg, Long time) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMsg(msg);
        result.setTime(time);
        return result;
    }

    public static <T> Result<T> ifResult(int rows) {
        return rows > 0 ? Result.success() : Result.error(MSG_ERROR);
    }

    public static boolean isSuccess(Result<?> result) {
        return result != null && SYSTEM_SUCCESS.equals(result.getCode());
    }

    public static boolean fail(Result<?> response) {
        return response == null || !SYSTEM_SUCCESS.equals(response.getCode());
    }
}
